package com.yisu.es.parser;
import com.yisu.es.model.EsQueries;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @className EsQueryParser
 * @description 解析xml文件
 * @author xuyisu
 * @date 2025/01/13
 */
public class EsQueryParser {
    /**
     * 解析指定文件路径中的ES查询对象
     *
     * @param filePath 文件路径
     * @return 解析后的EsQueries对象
     * @throws JAXBException JAXB异常
     */
    public static EsQueries parse(String filePath) throws JAXBException, FileNotFoundException {
        // 输入参数验证
        if (filePath == null || filePath.trim().isEmpty()) {
            throw new IllegalArgumentException("File path cannot be null or empty");
        }

        // 防止路径遍历攻击
        if (!filePath.startsWith("/")) {
            throw new IllegalArgumentException("File path must start with '/'");
        }

        try (InputStream inputStream = EsQueryParser.class.getResourceAsStream(filePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("Resource not found: " + filePath);
            }

            // 创建 JAXB 上下文和 Unmarshaller
            JAXBContext jaxbContext = JAXBContext.newInstance(EsQueries.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

            // 解析 XML 并返回结果
            return (EsQueries) jaxbUnmarshaller.unmarshal(new StreamSource(inputStream));
        } catch (JAXBException | IOException e) {
            throw new JAXBException("Failed to parse XML from " + filePath, e);
        }
    }

}


